package com.dc.java8.other.io;


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * Description: 资源关闭，去除 try–catch-finally 写法
 *
 * https://juejin.im/post/5e87cb9be51d4546cf777342
 *
 * @author: gdc
 * @date: 2020/4/5
 * @version 1.0
 */
public class ResourceCloseTest {

    /**
     * 资源关闭新写法， 去除 finally 方法
     */
    public static void main(String[] args) {
        // 当包含多个资源时，以 ';' 分割， 放在 try() 中
        try (BufferedReader br = new BufferedReader(new FileReader("/牛逼.txt"));
             BufferedReader br2 = new BufferedReader(new FileReader("/牛逼.txt"))){

            String str = null;
            while ((str =br.readLine()) != null) {
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 资源关闭原写法，包含 finally 方法
     */
    /*public static void main(String[] args) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("/牛逼.txt"));
            String str = null;
            while ((str =br.readLine()) != null) {
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }*/
}
